package com.mycity.semantic;

import java.io.IOException;






import com.amazonaws.util.json.JSONArray;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;

/**
 * The Freebase class uses Freebase API for finding semantically related words.
 * @author  Ahmet Erdem
 * @version December 2013 
 */
public class Freebase {

	public static final int LIMIT = 4;

	private static final String API_KEY = "AIzaSyDIO2lbCrilTAPn9ZBIU1PL6n46FxnqgEw";

	/**
	 * Finds related tags for a given tag.
	 * Tag category is written near the tag between the brackets. 
	 * @param tag input parameter 
	 * @param relatedTags output parameter which is list of tags related to given tag
	 * @param scores output parameter which is list of similarity scores matched to related tags
	 * @return length of related tags.
	 */
	public static int setScores(String tag, String relatedTags[], Double scores[]){
		try {
			JSONArray results = search(tag);
			int range = Math.min(results.length(),LIMIT);
			relatedTags[0] = tag;
			scores[0] = 1.0;
			double totalScore = 0;

			for(int i=1; i<range+1; i++){
				JSONObject relatedTag = results.getJSONObject(i-1);
				JSONObject notable = relatedTag.getJSONObject("notable");
				relatedTags[i] = relatedTag.getString("name")+ "("+notable.getString("name")+")";
				scores[i] = relatedTag.getDouble("score");
				totalScore+=scores[i];
			}

			for(int i=1; i<range+1; i++)
				scores[i]/=totalScore;

			return range+1;

		} catch (IOException e) {
		} catch (JSONException e) {
		} 
		return 0;

	}

	/**
	 * Searches for related words for a given word.
	 * @param tag found words must be related to this word.
	 * @exception IOException may occur while building get request
	 * @exception JSONException may occur while parsing json response
	 * @return JSONArray of words with name, category and score.
	 */
	private static JSONArray search(String tag) throws IOException, JSONException{
		HttpTransport httpTransport = new NetHttpTransport();
		HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
		GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/search");
		url.put("query", tag);
		url.put("limit", ""+LIMIT);
		url.put("key", API_KEY);
		HttpRequest request = requestFactory.buildGetRequest(url);
		HttpResponse httpResponse = request.execute();
		JSONObject response = new JSONObject( httpResponse.parseAsString());
		JSONArray results = response.getJSONArray("result");
		return results;


	}

}
